import {
  getTimeMillis,
  handleCheckRegister,
  handleLogin,
  handleRegister,
  handleResetPassword,
  loginByEmail,
  loginByMobile,
  registerByMobile,
  sendEmailCode,
  sendMobileCodeNT,
  sendResetCode,
} from '@/services/login';
import { Button, Card, Col, Divider, Form, Input, Row, Space, Tabs, message } from 'antd';

import logo from '@/assets/b_logo.png';
import email from '@/assets/email.png';
import icon from '@/assets/icon2.png';
import lock from '@/assets/lock.png';
import tel from '@/assets/tel_g.png';
import Locale from '@/components/SelectLang';
import { handleEvent } from '@/services/center';
import { emailPattern, passwordPattern, phonePattern } from '@/utils/common';
import { useEffect, useState } from 'react';
import { Helmet, getLocale, useIntl } from 'umi';
import PrivacyModal from '../Info/components/PrivacyModal';
import CodeModal from './components/CodeModal';

import CountrySelect from '@/components/CountrySelect';
import { jumpUrl } from '@/utils';
import './index.less';

let timer: any = null;
const Login: React.FC = () => {
  const intl = useIntl();
  const [form] = Form.useForm();
  const [visible, setVisible] = useState(false);
  const [isCodeLogin, setIsCodeLogin] = useState(false);
  //  防止频繁点击
  const [isClick, setIsClick] = useState(false);
  // 是否
  const [isFirstClick, setIsFirstClick] = useState(false);
  const [codeModalvisible, setCodeModalvisible] = useState(false);
  const [iserror, setIsError] = useState(false);
  //  1 2 登录  3 4 注册  5 6找回
  const [key, setKey] = useState('1');

  const [loading, setLoading] = useState(false);
  const [count, setCount] = useState(0);
  // 0登录，1注册，2重置
  const [index, setIndex] = useState(0);

  useEffect(() => {
    if (count == 59) {
      timer = setInterval(() => setCount((t) => t - 1), 1000);
    } else if (count <= 0) {
      clearInterval(timer);
    }
  }, [count]);
  useEffect(() => {
    setCount(0);
    setIsError(false);
    setIsFirstClick(false);
    form.resetFields();
  }, [index, key, form]);

  const getUserInfoFn = async () => {
    const { token = '' } = JSON.parse(localStorage.getItem('userInfo') || '{}');

    if (token) {
      jumpUrl('/');
    }
  };
  // 存在用户信息跳转回去
  useEffect(() => {
    getUserInfoFn();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  useEffect(() => {
    if ([0, 1].includes(index)) {
      const tag = index == 0 ? 'Log_on_access' : 'Register_access';
      handleEvent(tag);
    }
  }, [index]);

  const sendSuc = () => {
    setCount(59);
    setIsClick(false);
    setIsFirstClick(true);

    message.success(intl.formatMessage({ id: 'home.send_suc' }));
  };
  // 验证码
  const codeComponent = (type: string, valType?: number, sendType?: number) => {
    const isPhone = type == 'mobile';
    return (
      <Form.Item
        noStyle
        shouldUpdate={(prevValues, curValues) => prevValues[type] !== curValues[type]}
      >
        {({ getFieldValue }) => {
          const mobile = getFieldValue(type);
          return (
            <Form.Item
              label={intl.formatMessage({ id: 'login.captcha' })}
              rules={[{ required: true }]}
              name="captcha"
            >
              <Input
                suffix={
                  <>
                    <Divider type="vertical" />
                    <Button
                      disabled={!mobile || isClick || !!count}
                      onClick={async () => {
                        if (isClick || !!count) {
                          return false;
                        }

                        setIsClick(true);
                        const params = { valType };
                        try {
                          if (isPhone) {
                            await sendMobileCodeNT({
                              mobile,
                              ...params,
                            });
                          }
                          if (type == 'email') {
                            await sendEmailCode({ type: index, email: mobile, ...params });
                          }
                          if (type === 'account') {
                            if (index == 2) {
                              await sendResetCode({ account: mobile, ...params, sendType });
                            }
                            if (index == 0) {
                              if (key == '1') {
                                await sendMobileCodeNT({
                                  mobile,
                                  ...params,
                                });
                              }
                              if (key == '2') {
                                await sendEmailCode({ type: 1, email: mobile, ...params });
                              }
                            }
                          }
                          sendSuc();
                        } catch {
                          setIsClick(false);
                        }
                      }}
                      className="login_code_btn"
                      style={{
                        border: 'none',
                        background: 'none',
                        padding: '0',
                        boxShadow: 'none',
                        cursor: isClick || !!count ? 'auto' : 'pointer',
                      }}
                    >
                      {count == 0
                        ? isFirstClick
                          ? intl.formatMessage({ id: 'login.phone.send' })
                          : intl.formatMessage({ id: 'login.send' })
                        : intl.formatMessage({ id: 'login.count' }, { count: count })}
                    </Button>
                  </>
                }
                style={{ height: 50 }}
                placeholder={intl.formatMessage({ id: 'login.captcha' })}
              />
            </Form.Item>
          );
        }}
      </Form.Item>
    );
  };

  // 登入
  const loginItems = [
    {
      label: intl.formatMessage({ id: 'app.login_phone' }),
      key: '1',
      children: (
        <>
          <Form.Item
            label={intl.formatMessage({
              id: 'login.phone.input',
            })}
            rules={[{ required: true }, phonePattern]}
            name="account"
            validateTrigger="onBlur"
          >
            <Input
              prefix={
                <>
                  <img src={tel} width={14} style={{ marginRight: 14 }} />
                  <div style={{ color: '#333' }}>+852</div>
                </>
              }
              style={{ height: 50 }}
              placeholder={intl.formatMessage({
                id: 'login.phone.input',
              })}
            />
          </Form.Item>
          {!isCodeLogin ? (
            <Form.Item
              label={intl.formatMessage({ id: 'login.password' })}
              rules={[{ required: true }]}
              name="password"
            >
              <Input.Password
                maxLength={12}
                prefix={<img src={lock} width={20} style={{ marginRight: 10 }} />}
                style={{ height: 50 }}
                autoComplete="new-password"
                placeholder={intl.formatMessage({ id: 'login.password' })}
              />
            </Form.Item>
          ) : (
            codeComponent('account', 1)
          )}
        </>
      ),
    },
    {
      label: intl.formatMessage({ id: 'app.login_email' }),
      key: '2',
      children: (
        <>
          <Form.Item
            label={intl.formatMessage({ id: 'login.email' })}
            rules={[{ required: true }, emailPattern]}
            name="account"
            validateTrigger="onBlur"
          >
            <Input
              prefix={<img src={email} width={20} style={{ marginRight: 10 }} />}
              style={{ height: 50 }}
              placeholder={intl.formatMessage({ id: 'login.email' })}
            />
          </Form.Item>
          {!isCodeLogin ? (
            <Form.Item
              label={intl.formatMessage({ id: 'login.password' })}
              rules={[{ required: true }]}
              name="password"
            >
              <Input.Password
                maxLength={12}
                prefix={<img src={lock} width={20} style={{ marginRight: 10 }} />}
                style={{ height: 50 }}
                autoComplete="new-password"
                placeholder={intl.formatMessage({ id: 'login.password' })}
              />
            </Form.Item>
          ) : (
            codeComponent('account', 1)
          )}
        </>
      ),
    },
  ];
  // 注册和找回
  const resignComponents = (type: string, valType?: number, sendType?: any) => {
    return (
      <>
        {codeComponent(type, valType, sendType)}
        <Form.Item
          style={{ marginBottom: iserror ? 28 : 0 }}
          rules={[
            { required: true },
            {
              validator: (_, value) =>
                new Promise<void>((resolve, reject) => {
                  if (value) {
                    if (passwordPattern.pattern.test(value)) {
                      resolve();
                      setIsError(false);
                    } else {
                      setIsError(true);
                      reject(new Error(intl.formatMessage({ id: passwordPattern.message })));
                    }
                  } else {
                    setIsError(true);
                    reject();
                  }
                }),
            },
          ]}
          label={intl.formatMessage({ id: 'login.password' })}
          name="password"
          validateTrigger="onBlur"
        >
          <Input.Password
            maxLength={12}
            prefix={<img src={lock} width={20} />}
            style={{ height: 50 }}
            autoComplete="new-password"
            placeholder={intl.formatMessage({ id: 'login.password_holder' })}
          />
        </Form.Item>
        {!iserror ? (
          <div style={{ margin: '0 0 14px 0', letterSpacing: '-0.5px' }}>
            {intl.formatMessage({ id: 'home.password_style' })}
          </div>
        ) : null}
        <Form.Item
          noStyle
          shouldUpdate={(prevValues, curValues) => prevValues.password !== curValues.password}
        >
          {({ getFieldValue }) => {
            const password = getFieldValue('password');
            return (
              <Form.Item
                validateTrigger="onBlur"
                rules={[
                  { required: true },
                  {
                    validator: (_, value) =>
                      new Promise<void>((resolve, reject) => {
                        if (value) {
                          if (password === value) {
                            resolve();
                          } else {
                            reject(
                              new Error(
                                intl.formatMessage({ id: 'app.configuration.password_same' }),
                              ),
                            );
                          }
                        } else {
                          reject();
                        }
                      }),
                  },
                ]}
                label={intl.formatMessage({ id: 'validation.confirm-password.required' })}
                name="password_confirmation"
              >
                <Input.Password
                  maxLength={12}
                  prefix={<img src={lock} width={20} />}
                  style={{ height: 50 }}
                  autoComplete="new-password"
                  placeholder={intl.formatMessage({ id: 'validation.confirm-password.required' })}
                />
              </Form.Item>
            );
          }}
        </Form.Item>
      </>
    );
  };
  // 注册
  const resignItems = [
    {
      label: intl.formatMessage({ id: 'app.phone_email' }),
      key: '3',
      children: (
        <>
          <Form.Item
            label={intl.formatMessage({
              id: 'login.phone.input',
            })}
            rules={[
              { required: true },
              {
                validator: (_, value) =>
                  new Promise<void>(async (resolve, reject) => {
                    if (value) {
                      if (phonePattern.pattern.test(value)) {
                        const { code } = await handleCheckRegister({ account: value, type: 1 });
                        if (code == '100200') {
                          resolve();
                        } else {
                          reject(
                            <span style={{ color: 'red' }}>
                              {intl.formatMessage({ id: 'home.login.phoneRegister' })}
                            </span>,
                          );
                        }
                      } else {
                        reject(new Error(intl.formatMessage({ id: phonePattern.message })));
                      }
                    } else {
                      reject();
                    }
                  }),
              },
            ]}
            name="mobile"
            validateTrigger="onBlur"
          >
            <Input
              prefix={
                <>
                  <img src={tel} width={14} style={{ marginRight: 14 }} />
                  <div style={{ color: '#333' }}>+852</div>
                </>
              }
              style={{ height: 50 }}
              placeholder={intl.formatMessage({
                id: 'login.phone.input',
              })}
            />
          </Form.Item>
          {resignComponents('mobile', 2)}
        </>
      ),
    },
    {
      label: intl.formatMessage({ id: 'app.resign_email' }),
      key: '4',
      children: (
        <>
          <Form.Item
            label={intl.formatMessage({ id: 'login.email' })}
            rules={[
              { required: true },
              {
                validator: (_, value) =>
                  new Promise<void>(async (resolve, reject) => {
                    if (value) {
                      if (emailPattern.pattern.test(value)) {
                        const { code } = await handleCheckRegister({ account: value, type: 2 });
                        if (code == '100200') {
                          resolve();
                        } else {
                          reject(
                            <span style={{ color: '#000' }}>
                              {intl.formatMessage({ id: 'home.login.emailRegister' })}
                            </span>,
                          );
                        }
                      } else {
                        reject(new Error(intl.formatMessage({ id: emailPattern.message })));
                      }
                    } else {
                      reject();
                    }
                  }),
              },
            ]}
            name="email"
            validateTrigger="onBlur"
          >
            <Input
              prefix={<img src={email} width={20} />}
              style={{ height: 50 }}
              placeholder={intl.formatMessage({ id: 'login.email' })}
            />
          </Form.Item>

          {resignComponents('email', 2)}
        </>
      ),
    },
  ];
  // 找回

  const findItems = [
    {
      label: intl.formatMessage({ id: 'home.phone_find' }),
      key: '5',
      children: (
        <>
          <Form.Item
            label={intl.formatMessage({
              id: 'login.phone.input',
            })}
            rules={[{ required: true }, phonePattern]}
            name="account"
            validateTrigger="onBlur"
          >
            <Input
              prefix={
                <>
                  <img src={tel} width={14} style={{ marginRight: 14 }} />
                  <div style={{ color: '#333' }}>+852</div>
                </>
              }
              style={{ height: 50 }}
              placeholder={intl.formatMessage({
                id: 'login.phone.input',
              })}
            />
          </Form.Item>
          {resignComponents('account', 3, 1)}
        </>
      ),
    },
    {
      label: intl.formatMessage({ id: 'home.email_find' }),
      key: '6',
      children: (
        <>
          <Form.Item
            label={intl.formatMessage({ id: 'login.email' })}
            rules={[{ required: true }, emailPattern]}
            name="account"
            validateTrigger="onBlur"
          >
            <Input
              prefix={<img src={email} width={20} />}
              style={{ height: 50 }}
              placeholder={intl.formatMessage({ id: 'login.email' })}
            />
          </Form.Item>
          {resignComponents('account', 3, 2)}
        </>
      ),
    },
  ];

  const poinitItem = [
    {
      top: '30%',
      right: '72%',
      animationDelay: '.25s',
      isBlue: true,
    },
    {
      top: '35.5%',
      right: '72.5%',
      animationDelay: '.125s',
      isBlue: true,
    },
    {
      top: '41.5%',
      right: '70.5%',
      animationName: 'move1',
      animationDelay: '.5s',
      width: 12,
      height: 12,
    },
    {
      top: '44.5%',
      right: '70.5%',
      width: 16,
      height: 16,
    },
    {
      top: '46%',
      right: '66.5%',

      width: 14,
      height: 14,
    },
    {
      isBlue: true,
      top: '30%',
      right: '72%',
      animationDelay: '.25s',
    },
    {
      isBlue: true,
      top: '34%',
      right: '30%',
      animationDelay: '.25s',
    },
    {
      isBlue: true,
      top: '42%',
      right: '30%',
      animationDelay: '.5s',
      width: 12,
      animationName: 'move1',
      height: 12,
    },
    {
      isBlue: true,
      top: '50%',
      right: '24%',
      animationDelay: '.5s',
      width: 12,
      height: 12,
    },
    {
      top: '47%',
      right: '31%',
      animationDelay: '.5s',
      width: 12,
      height: 12,
    },
    {
      top: '55%',
      right: '31.5%',
      animationDelay: '1s',
      width: 16,
      height: 16,
      animationName: 'move1',
    },
    {
      top: '55%',
      right: '38.5%',
      animationDelay: '1s',
      width: 20,
      height: 20,
      animationName: 'move1',
    },
  ];
  const isEn = getLocale() == 'en-US';
  return (
    <>
      <Helmet>
        <title>{intl.formatMessage({ id: 'home.login_meta_title' })}</title>
      </Helmet>
      <div className="login_warrper">
        <Row className="login">
          <Col className="login_left">
            {/* 圆点 */}
            {poinitItem.map((item, index) => {
              const { isBlue } = item;
              return (
                <div
                  // eslint-disable-next-line react/no-array-index-key
                  key={index}
                  style={item}
                  className={!isBlue ? 'login_bg_blue' : 'login_blue'}
                />
              );
            })}

            <div className="login_left_content">
              <Space size={6} align="center">
                <img
                  style={{ cursor: 'pointer' }}
                  onClick={() => {
                    jumpUrl('/');
                  }}
                  src={logo}
                  height={43}
                />
                <CountrySelect dark />
              </Space>
            </div>
          </Col>

          <Col className="login_right">
            <div
              style={{
                display: 'flex',
                justifyContent: 'flex-end',
                position: 'absolute',
                zIndex: 10,
                right: 90,
                top: 52,
              }}
            >
              <Locale
                localOverlayClassName="info_local_class"
                wordCss={{ color: '#999' }}
                icons={icon}
              />
            </div>
            <Form
              onFinish={async (values: Login.LoginParams & { account: string; mobile: string }) => {
                setLoading(true);

                let newVal: Login.LoginParams & { account: string; mobile: string; type?: string };
                if (index == 0 && isCodeLogin) {
                  const { account, ...rest } = values;
                  const newKey = key == '1' ? 'mobile' : 'email';
                  newVal = { [newKey]: account, ...rest } as any;
                } else {
                  if (index == 0) {
                    // 1 手机  2 邮箱
                    newVal = { type: key, ...values };
                  } else {
                    newVal = values;
                  }
                }
                const fn =
                  index == 0
                    ? isCodeLogin
                      ? key == '1'
                        ? loginByMobile
                        : loginByEmail
                      : handleLogin
                    : index == 1
                    ? key == '3'
                      ? registerByMobile
                      : handleRegister
                    : handleResetPassword;
                try {
                  const { code, data, message: ms } = await fn(newVal);
                  setLoading(false);
                  if (code === '100200') {
                    if (index == 2) {
                      setIndex(0);
                      setKey('1');
                      message.success(ms);
                      return;
                    }
                    const tag = index == 0 ? 'Log_on_log' : 'Register_register';
                    handleEvent(tag);
                    const { data: val } = await getTimeMillis();
                    const time = new Date().getTime();
                    const token = (data as any)?.token || data;
                    localStorage.setItem(
                      'userInfo',
                      JSON.stringify({
                        ti: Number(val?.timestamp) - time,
                        token,
                      }),
                    );

                    if (typeof data == 'string') {
                      jumpUrl('/');
                    } else {
                      if ((data as any).jumpIndex) {
                        jumpUrl('/');
                      } else {
                        jumpUrl('/product');
                      }
                    }

                    // message.success(ms);
                  }
                } catch {
                  setLoading(false);
                }
              }}
              name="dependencies"
              form={form}
              labelCol={{ span: 0 }}
              className="login_right_form"
            >
              <>
                <Card className="login_right_card">
                  <div style={{ fontSize: 36, fontWeight: 700, lineHeight: '48px' }}>
                    {intl.formatMessage({
                      id:
                        index == 2
                          ? 'app.login.find'
                          : index == 0
                          ? 'home.user_login'
                          : 'home.user_resiter',
                    })}
                  </div>

                  <Tabs
                    destroyInactiveTabPane
                    activeKey={key}
                    onChange={(key) => {
                      setKey(key);

                      form.resetFields();
                    }}
                    items={index === 0 ? loginItems : index == 1 ? resignItems : findItems}
                  />

                  <div className="login_right_action">
                    {/* 登录 */}
                    {index == 0 && (
                      <>
                        <div
                          className="login_right_remeber"
                          onClick={() => {
                            setIsCodeLogin(!isCodeLogin);
                          }}
                        >
                          {intl.formatMessage({
                            id: !isCodeLogin
                              ? 'login.phone.login_code'
                              : 'login.phone.login_password',
                          })}
                        </div>
                        <div
                          className="login_right_forget"
                          onClick={() => {
                            setIndex(2);
                            setKey('5');
                          }}
                        >
                          {intl.formatMessage({ id: 'login.forget' })}
                        </div>
                      </>
                    )}
                  </div>
                  <Button
                    htmlType="submit"
                    style={{
                      height: 60,
                      color: '#fff',
                      margin: '18px 0 12px 0',
                      borderRadius: 30,
                    }}
                    loading={loading}
                    type="primary"
                    block
                    className="login_right_btn"
                  >
                    {intl.formatMessage({
                      id: index == 0 ? 'login.login' : index == 2 ? 'login.rest' : 'login.sure',
                    })}
                  </Button>

                  {index != 2 && (
                    <div
                      style={{ marginBottom: 18, fontSize: isEn ? 12 : 14, wordBreak: 'break-all' }}
                    >
                      <span> {intl.formatMessage({ id: 'home.login_server' })}</span>
                      <span
                        onClick={() => {
                          setVisible(true);
                        }}
                        className="login_right_common_word"
                      >
                        {intl.formatMessage({ id: 'login.private' })}
                      </span>
                      <span style={{ color: '#000', margin: '0 4px' }}>
                        {intl.formatMessage({ id: 'home.and' })}
                      </span>
                      <span
                        onClick={() => {
                          setVisible(true);
                        }}
                        className="login_right_common_word"
                      >
                        {intl.formatMessage({ id: 'home.condition' })}
                      </span>
                    </div>
                    // <Form.Item
                    //   className="checkbox"
                    //   style={{ marginBottom: 20 }}
                    //   rules={[
                    //     {
                    //       validator: (_, value) =>
                    //         value
                    //           ? Promise.resolve()
                    //           : Promise.reject(
                    //               new Error(intl.formatMessage({ id: 'home.accept_private' })),
                    //             ),
                    //     },
                    //   ]}
                    //   valuePropName="checked"
                    //   name="btnChecked"
                    // >
                    //   <Checkbox>

                    //   </Checkbox>
                    // </Form.Item>
                  )}

                  {/* 底部文字 */}
                  <div style={{ color: '#666', fontSize: 16 }}>
                    {/* 注册 */}
                    {index === 0 ? (
                      <>
                        {intl.formatMessage({ id: 'login.no_account' })}
                        <span
                          className="login_right_word"
                          style={{ marginLeft: 4 }}
                          onClick={() => {
                            setIndex(1);
                            setKey('3');
                            handleEvent('Log_on_register');
                          }}
                        >
                          {intl.formatMessage({ id: 'login.registered' })}
                        </span>
                      </>
                    ) : (
                      <Row justify="space-between">
                        <Col>
                          <span
                            onClick={() => {
                              setCodeModalvisible(true);
                            }}
                            className="login_right_word"
                          >
                            {intl.formatMessage({ id: 'login.get_number' })}
                          </span>
                        </Col>
                        <Col style={{ fontSize: 16 }}>
                          {intl.formatMessage({ id: 'login.have_account' })}
                          <span
                            className="login_right_word"
                            onClick={() => {
                              if (index == 1) {
                                handleEvent('Register_log');
                              }
                              setKey('1');
                              setIndex(0);
                            }}
                          >
                            {intl.formatMessage({ id: 'login.login_in' })}
                          </span>
                        </Col>
                      </Row>
                    )}
                  </div>
                </Card>
              </>
            </Form>
          </Col>
          {/* 隐私策略弹窗 */}
          <PrivacyModal
            visible={visible}
            handleCancel={() => {
              setVisible(false);
            }}
          />
          {/* 验证码弹窗 */}
          <CodeModal
            type={['5', '3'].includes(key) ? 'mobile' : 'email'}
            visible={codeModalvisible}
            handleCancel={() => {
              setCodeModalvisible(false);
            }}
          />
        </Row>
      </div>
    </>
  );
};

export default Login;
